using System;
using System.Collections.Generic;
using GTA;
using GTA.Math;

namespace CustomPeds;

public class Behavior : Script
{
	private List<Ped> enemiesList = new List<Ped>();
	
	// 优化：添加缓存和检查间隔
	private DateTime lastEnemyCheck = DateTime.MinValue;
	private DateTime lastFollowCheck = DateTime.MinValue;
	private readonly TimeSpan enemyCheckInterval = TimeSpan.FromSeconds(2);
	private readonly TimeSpan followCheckInterval = TimeSpan.FromSeconds(1);
	
	// 优化：缓存附近Ped信息
	private Ped[] cachedNearbyPeds = new Ped[0];
	private DateTime lastPedCache = DateTime.MinValue;
	private readonly TimeSpan pedCacheInterval = TimeSpan.FromSeconds(3);

	public Behavior()
	{
		Tick += OnTick;
		Interval = 1000; // 保持1秒间隔
	}

	private void OnTick(object sender, EventArgs e)
	{
		try
		{
			if (Main.P2.Character != null && Main.P2.Character.IsAlive)
			{
				if (!Main.IsPedDriverOfCurrentVehicle(Main.P2.Character) && Main.P2.AutoAttack)
				{
					AttackNearbyEnemies();
				}
				if (Main.P2.Follow)
				{
					CheckFollow();
				}
				CheckIsInvincible();
			}
			// 女友开车模式下强制司机为女友、主角为乘客
			if (Main.P2.IsTaskDriveToWaypoint)
			{
				EnforceGirlfriendDriverState();
			}
			CheckCanWearHelmet();
			CheckDrivingStyle();
			CheckChangeSeat();
		}
		catch (Exception ex)
		{
			LogHelper.WriteException(ex, "Behavior.OnTick - 主要行为检查");
			UI.Notify($"行为脚本错误: {ex.Message}");
		}
	}

	private void EnforceGirlfriendDriverState()
	{
		try
		{
			Vehicle vehicle = null;
			if (Main.P1.Character != null && Main.P1.Character.IsInVehicle())
			{
				vehicle = Main.P1.Character.CurrentVehicle;
			}
			else if (Main.P2.Character != null && Main.P2.Character.IsInVehicle())
			{
				vehicle = Main.P2.Character.CurrentVehicle;
			}
			if (vehicle == null || !vehicle.Exists())
			{
				return;
			}
			// 如果主角在主驾驶或女友不在主驾驶，则纠正
			if (Main.IsPedDriverOfCurrentVehicle(Main.P1.Character) || !Main.IsPedDriverOfCurrentVehicle(Main.P2.Character))
			{
				Main.EnsureDriverAndPassenger(vehicle, Main.P2.Character, Main.P1.Character);
			}
		}
		catch (Exception ex)
		{
			LogHelper.WriteException(ex, "EnforceGirlfriendDriverState - 强制女友为司机");
		}
	}

	private void CheckCanWearHelmet()
	{
		try
		{
			if (Main.P1.Character != null && Main.P1.Character.IsAlive && !Main.P1.CanWearHelmet)
			{
				Main.P1.Character.RemoveHelmet(instantly: true);
			}
			if (Main.P2.Character != null && Main.P2.Character.IsAlive && !Main.P2.CanWearHelmet)
			{
				Main.P2.Character.RemoveHelmet(instantly: true);
			}
		}
		catch (Exception ex)
		{
			LogHelper.WriteException(ex, "CheckCanWearHelmet - 头盔检查");
		}
	}

	private void CheckIsInvincible()
	{
		try
		{
			if (Main.P2.Invincible)
			{
				Main.P2.Character.IsInvincible = true;
			}
			else
			{
				Main.P2.Character.IsInvincible = false;
			}
		}
		catch (Exception ex)
		{
			LogHelper.WriteException(ex, "CheckIsInvincible - 无敌状态检查");
		}
	}

	private void CheckDrivingStyle()
	{
		try
		{
			if (Main.P1.Character != null && Main.P1.Character.IsAlive && Main.P1.drivingStyle != DrivingStyle.Rushed)
			{
				Main.P1.Character.DrivingStyle = Main.P1.drivingStyle;
			}
			if (Main.P2.Character != null && Main.P2.Character.IsAlive && Main.P2.drivingStyle != DrivingStyle.Rushed)
			{
				Main.P2.Character.DrivingStyle = Main.P2.drivingStyle;
			}
		}
		catch (Exception ex)
		{
			LogHelper.WriteException(ex, "CheckDrivingStyle - 驾驶风格检查");
		}
	}

	private void CheckChangeSeat()
	{
		try
		{
			// P1：检查并尝试换到目标座位（基于自身当前车辆）
			if (Main.P1.Character != null && Main.P1.Character.IsAlive && Main.P1.Character.IsInVehicle() && !Main.P1.IsTaskDriveToWaypoint)
			{
				var p1Vehicle = Main.P1.Character.CurrentVehicle;
				var p1TargetSeat = (VehicleSeat)Main.P1.SeatIndex;
				if (p1Vehicle != null && p1Vehicle.Exists() && !Main.IsPedInSeat(p1Vehicle, Main.P1.Character, p1TargetSeat))
				{
					bool p1SeatFree = Main.IsSeatFree(p1Vehicle, p1TargetSeat);
					if (p1SeatFree)
					{
						Main.P1.Character.Task.EnterVehicle(p1Vehicle, p1TargetSeat, 3000, 2f, 16);
					}
				}
			}

			// P2：检查并尝试换到P1车辆的目标座位（当P1在车内时）
			if (Main.P2.Character != null && Main.P2.Character.IsAlive && Main.P2.Character.IsInVehicle() && !Main.P2.IsTaskDriveToWaypoint)
			{
				if (Main.P1.Character != null && Main.P1.Character.IsAlive && Main.P1.Character.IsInVehicle())
				{
					var targetVehicle = Main.P1.Character.CurrentVehicle;
					var p2TargetSeat = (VehicleSeat)Main.P2.SeatIndex;
					if (targetVehicle != null && targetVehicle.Exists() && !Main.IsPedInSeat(targetVehicle, Main.P2.Character, p2TargetSeat))
					{
						bool p2SeatFree = Main.IsSeatFree(targetVehicle, p2TargetSeat);
						if (p2SeatFree)
						{
							Main.P2.Character.Task.EnterVehicle(targetVehicle, p2TargetSeat, 3000, 2f, 16);
						}
					}
				}
			}
		}
		catch (Exception ex)
		{
			LogHelper.WriteException(ex, "CheckChangeSeat - 换座检查");
		}
	}

	private void CheckFollow()
	{
		// 优化：减少检查频率
		if (DateTime.Now.Subtract(lastFollowCheck) < followCheckInterval)
		{
			return;
		}
		lastFollowCheck = DateTime.Now;
		
		try
		{
			if (Main.P1.Character != null && Main.P2.Character != null && 
				Main.P1.Character.Position.DistanceTo(Main.P2.Character.Position) > 20f) // 从35f缩小到20f
			{
				Main.P2.Character.Position = Main.P1.Character.GetOffsetInWorldCoords(new Vector3(0f, -3f, -1f)); // 从-4f调整到-3f，让女友更靠近
				if (!Main.P1.Character.CurrentPedGroup.Contains(Main.P2.Character))
				{
					Main.P1.Character.CurrentPedGroup.Add(Main.P2.Character, leader: false);
				}
			}
		}
		catch (Exception ex)
		{
			LogHelper.WriteException(ex, "CheckFollow - 跟随检查");
		}
	}

	private void AttackNearbyEnemies()
	{
		// 优化：减少检查频率
		if (DateTime.Now.Subtract(lastEnemyCheck) < enemyCheckInterval)
		{
			return;
		}
		lastEnemyCheck = DateTime.Now;
		
		try
		{
			// 优化：缓存附近Ped信息
			if (DateTime.Now.Subtract(lastPedCache) >= pedCacheInterval)
			{
				cachedNearbyPeds = World.GetNearbyPeds(Game.Player.Character.Position, 35f);
				lastPedCache = DateTime.Now;
			}
			
			// 清理已死亡的敌人
			enemiesList.RemoveAll(ped => ped == null || !ped.Exists() || ped.IsDead);
			
			foreach (Ped ped in cachedNearbyPeds)
			{
				if (ped == null || !ped.Exists())
				{
					continue;
				}
				
				if (ped.IsAlive && ped.Handle != Game.Player.Character.Handle && 
					ped.Handle != Main.P2.Character.Handle && 
					(ped.IsInCombatAgainst(Main.P1.Character) || ped.IsInCombatAgainst(Main.P2.Character)))
				{
					// 检查是否已经在敌人列表中
					if (!enemiesList.Exists(p => p.Handle == ped.Handle))
					{
						Main.P2.Character.Task.FightAgainst(ped);
						enemiesList.Add(ped);
					}
				}
			}
		}
		catch (Exception ex)
		{
			LogHelper.WriteException(ex, "AttackNearbyEnemies - 攻击附近敌人");
		}
	}
}
